package top.hzy520.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.hzy520.common.constants.Constants;
import top.hzy520.common.resp.ApiResult;

import java.util.List;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 22:00 2018/5/13
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionHandlerAdvice {
    @ExceptionHandler(Exception.class)
    public ApiResult handlerException(Exception e){
        log.error(e.getMessage(),e);
        return new ApiResult(Constants.RESP_STATUS_INTERNAL_ERROR,"系统异常稍后再试");
    }
    @ExceptionHandler(YuyuBuyException.class)
    public ApiResult handlerException(YuyuBuyException e){
        log.error(e.getMessage(),e);
        return new ApiResult(e.getStatusCode(),e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult handlerIllegalParamException(MethodArgumentNotValidException e){
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String message= "参数不合法";
        if (errors.size()>0){
            message = errors.get(0).getDefaultMessage();
        }
        ApiResult result=new ApiResult(Constants.RESP_STATUS_BADREQUEST,e.getMessage());
        return result;
    }
}
